package ro.msg.office.ticketmanager.back.bean;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import ro.msg.office.entities.Department;
import ro.msg.office.ticketmanager.DO.DepartmentDO;
import ro.msg.office.ticketmanager.back.ifc.DepartmentManager;

	/********************************************************
		*@Stateless session bean instances can be pooled and 
			may be shared between clients.When a client 
			invokes a method in a stateless session bean,the
			container either creates a new instance for the 
			client or assigns one from the bean. The instance
			is returned to the pool after use.
		*@TransactionManagement the container should manage 
			transactions on the beanâ€™s behalf
	 ********************************************************/

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DepartmentManagerBean implements DepartmentManager{
	
	Logger logger = Logger.getLogger(DepartmentManagerBean.class);
	/******************************************
		Injects EntityManager instance 
	******************************************/
	@PersistenceContext(unitName="TM_PU")
	private EntityManager em;


	public void createDepartment(String name) {
		Department department = new Department();
		department.setName(name);
		em.persist(department);
		logger.info("Department created with info: " + department.getName());
	}

	/**
	 * Persists entity instance  
	 * @param departmentName
	 * @return Department
	 */
	public Department findDepartmentByName(String departmentName){
		Query query = em.createNamedQuery("Department.findByName");
		query.setParameter("name", departmentName);
		Department department = (Department)query.getSingleResult();
		return department;
	}

	/**
	 * Find a all departments by Name
	 * @param
	 * @return Set<Department>
	 */
	public Set<Department> getDepartments() {
		Query query = em.createNamedQuery("Department.findAll");
		List<Department> departments = query.getResultList();
		Set<Department> departmentSet = new HashSet<Department>(departments);
		return departmentSet;
	}

	/**
	 * Map Department to DepartmentDO 
	 * @param Department
	 * @return DepartmentDO
	 */
	public DepartmentDO mapDepartmentToDO(Department d){
		DepartmentDO departmentDo = new DepartmentDO();
		departmentDo.setName(d.getName());
		departmentDo.setId(d.getDepartmentId());
		return departmentDo;
		
	}
	
}

